import 'package:flutter_dva/flutter_dva.dart';

class HomeModel implements Model<CountState> {
  /// 加1
  static String incrementCounter = "incrementCounter";

  @override
  Map<String, EffectFunction> effects = <String, EffectFunction>{
    incrementCounter:  (DvaAction action, ModelEffects effects) async {
      var tmpl = effects.getCurrentState() as CountState;
      await Future<dynamic>.delayed(const Duration(microseconds: 450));
      tmpl.count = (tmpl.count ?? 1) + 1;
      effects.dispatch(DvaAction("save", tmpl));
    }
  };

  @override
  String namespace = "home";

  @override
  Map<String, ReducerFuction> reducers = <String, ReducerFuction>{
    'save': (StoreOfState<dynamic> lastState, DvaAction action) {
      lastState.setState(action.payload);
      return lastState;
    }
  };

  @override
  StoreOfState<CountState> state = StoreOfState<CountState>(state: CountState());
}

class CountState extends DvaState {
  CountState({this.count = 1});
  num? count;

  @override
  void fromJson(Map<String,dynamic> json) {
    count = json['count'];
  }
  @override
  Map<String,dynamic> toJson() =><String,dynamic>{
    'count': count,
  };
}